
import Vue from 'vue'
import axios from 'axios'
import { Message, Loading, MessageBox } from 'element-ui'
import _ from 'lodash';
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '@/router'

//loading对象
let loading;
let that = this
//当前正在请求的数量
let needLoadingRequestCount = 0;

//显示loading加载中
function showLoading(target) {
  // 后面这个判断很重要，因为关闭时加了抖动，此时loading对象可能还存在，
  // 但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Loading.service({
      lock: true,
      text: "数据加载中，请稍后...",
      background: 'rgba(255, 255, 255, 0.95)',
      // target:  document.querySelector(target) || document.querySelector(".container"),
      target: target || ".container",
    });
  }
  needLoadingRequestCount++;
}

//隐藏loading
function hideLoading() {
  needLoadingRequestCount--;
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); //做个保护
  if (needLoadingRequestCount === 0) {
    //关闭loading
    toHideLoading();
  }
}
//防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
var toHideLoading = _.debounce(() => {
  if (loading) {
    loading.close();
    loading = null
  }
}, 300);

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API

  , // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = getToken()
    }
    //判断当前请求是否设置了不显示Loading
    if (config.headers.showLoading !== false) {
      showLoading(config.headers.loadingTarget);
    }

    return config
  },
  error => {
    // do something with request error

    console.log(error) // for debug
    //判断当前请求是否设置了不显示Loading
    if (config.headers.showLoading !== false) {
      hideLoading();
    }
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   * 
   */
  response => {

    const res = response.data
    const {
      config
    } = response

    //判断当前请求是否设置了不显示Loading
    if (response.config.headers.showLoading !== false) {
      hideLoading();
    }
    if (res.code !== '0000') {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === '1001') {
        MessageBox.confirm('您的登录状态已经失效，请重新登录!', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
     
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug

    //判断当前请求是否设置了不显示Loading
    if (error.config.headers.showLoading !== false) {
      hideLoading();
    }
    Message({
      message: error.msg,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
